package com.proxy.server.frontend.handler.request.select;

import com.proxy.parser.tree.sql.ast.expr.SQLIdentifierExpr;
import com.proxy.parser.tree.sql.ast.expr.SQLPropertyExpr;
import com.proxy.parser.tree.sql.ast.statement.SQLExprTableSource;
import com.proxy.parser.tree.sql.ast.statement.SQLSelect;
import com.proxy.parser.tree.sql.ast.statement.SQLSelectStatement;
import com.proxy.parser.tree.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock;
import com.proxy.parser.tree.sql.dialect.mysql.ast.statement.MySqlShowColumnsStatement;
import com.proxy.parser.tree.sql.dialect.mysql.ast.statement.MySqlShowCreateTableStatement;
import com.proxy.parser.tree.sql.dialect.mysql.ast.statement.MySqlShowIndexesStatement;

/**
 * Created by liufish on 16/7/31.
 */
public class ProxySqlReplaceUtil {


    /**
     * 如果,查询语句用带有
     * 将查询语句内置的数据库切换掉。
     *
     */
    public static void replaceSchema(SQLSelectStatement sqlSelectStatement,String schema){
        SQLSelect select = sqlSelectStatement.getSelect();
        MySqlSelectQueryBlock query = (MySqlSelectQueryBlock)select.getQuery();
        if(query.getFrom() != null){
            SQLExprTableSource source =  (SQLExprTableSource)query.getFrom();
            if(source.getExpr() != null){
                SQLPropertyExpr expr = (SQLPropertyExpr) source.getExpr();
                SQLIdentifierExpr owner = (SQLIdentifierExpr)expr.getOwner();
                if(expr.getOwner() != null){
                    owner.setName(schema);
                }
            }

        }
    }




    public static void replaceShowCreateTableSchema(MySqlShowCreateTableStatement statement,String schema){

        if(statement.getName()!= null){
            SQLPropertyExpr  expr = (SQLPropertyExpr) statement.getName();
            if(expr.getOwner() != null){
                SQLIdentifierExpr owner = (SQLIdentifierExpr)expr.getOwner();
                if(expr.getOwner() != null){
                    owner.setName(schema);
                }
            }

        }


    }



    public static void replaceShowColumnsStatement(MySqlShowColumnsStatement statement,String schema){

        if(statement.getDatabase() != null){
            SQLIdentifierExpr sqlIdentifierExpr = (SQLIdentifierExpr)statement.getDatabase();
            if(sqlIdentifierExpr != null){
                sqlIdentifierExpr.setName(schema);
            }
        }

    }

    public static void replaceShowIndexesStatement(MySqlShowIndexesStatement  statement, String schema){

        if(statement.getDatabase() != null){
            SQLIdentifierExpr sqlIdentifierExpr = (SQLIdentifierExpr)statement.getDatabase();
            if(sqlIdentifierExpr != null){
                sqlIdentifierExpr.setName(schema);
            }
        }

    }


}
